﻿using System;
using System.Globalization;
using System.Windows.Data;

namespace Windows.Toolkit
{
    public class BooleanEnumConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            bool result = false;

            try
            {
                if (value != null)
                {
                    bool handled = false;

                    Type valueType = value.GetType();

                    if (valueType.IsGenericType &&
                        valueType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                    {
                        if (Object.Equals(value, null))
                        {
                            handled = true;
                        }
                    }

                    if (!handled && parameter != null)
                    {
                        object parameterEnumValue = Enum.Parse(value.GetType(), parameter.ToString(), false);

                        if (Object.Equals(value, parameterEnumValue))
                        {
                            result = true;
                        }
                    }
                }
            }
            catch
            {
            }

            return result;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (targetType == null || parameter == null)
            {
                throw new InvalidOperationException("Parameters are not valid.");
            }

            if (Object.Equals(value, true))
            {
                Type enumType = targetType;

                if (targetType.IsGenericType &&
                    targetType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                {
                    enumType = Nullable.GetUnderlyingType(targetType);
                }

                return Enum.Parse(enumType, parameter.ToString(), false);
            }
            else
            {
                if (targetType.IsGenericType &&
                    targetType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                {
                    return null;
                }
                else
                {
                    return Activator.CreateInstance(targetType);
                }
            } 
        }

        #endregion
    }
}
